import axios from 'axios'
// console.log(3,process.env.REACT_APP_BASE_URL)
import { setToken } from '@/store/user'
// import { useDispatch } from "react-redux"
import store from '@/store/index'
import { message as msg } from 'antd';



const server = axios.create({
    baseURL: '/api',
    timeout: 5000,
})

// 请求拦截
server.interceptors.request.use((config)=>{
    // 添加请求头 token
    let token = localStorage.getItem('hr-token')
    if(token){
        config.headers.Authorization = 'Bearer ' + token
    }
    return config
},(err)=>{
    return Promise.reject(err)
})
// 响应拦截
server.interceptors.response.use((response)=>{
    const {data: { data: result, success, message}} = response
    if(success){
        if(response.config.method != 'get'){
            msg.success(message)
        }
        return result
    }else{
        msg.error(message)
        return Promise.reject(new Error(message))
    }
},(err)=>{
    if(err.response?.status === 401){
        // console.dir(err)
        store.dispatch(setToken(''))
        msg.error(err.response.data.message)
        return Promise.reject(new Error(err.response.data.message))
    }
    return Promise.reject(err)
})

export default server